package com.travel.travel_springboot_web.controller;

import com.travel.travel_springboot_web.entity.Order;
import com.travel.travel_springboot_web.service.OrderService;
import com.travel.travel_springboot_web.utils.JwtUtil;
import com.travel.travel_springboot_web.utils.TokenUtil;
import com.travel.travel_springboot_web.mapper.UserMapper;
import com.travel.travel_springboot_web.mapper.AddressMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/orders")
@CrossOrigin(
    originPatterns = {"http://localhost:*", "http://127.0.0.1:*"},
    methods = {
        RequestMethod.GET, 
        RequestMethod.POST, 
        RequestMethod.PUT, 
        RequestMethod.DELETE, 
        RequestMethod.OPTIONS
    },
    allowCredentials = "true"
)
public class OrderController {
    
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private TokenUtil tokenUtil;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private AddressMapper addressMapper;
    
    @GetMapping("/list")
    public Map<String, Object> list(
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            
            // 从token中获取用户ID和角色
            Long userId = jwtUtil.getUserIdFromToken(token);
            Integer role = jwtUtil.getRoleFromToken(token);
            logger.info("Getting order list for user: {}, role: {}, status: {}, keyword: {}, date range: {} to {}", 
                userId, role, status, keyword, startDate, endDate);
            
            if (userId == null) {
                throw new RuntimeException("请先登录");
            }
            
            List<Order> orders = orderService.getOrderList(userId, status, role, keyword, startDate, endDate);
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", orders);
        } catch (Exception e) {
            logger.error("Failed to get order list: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @PostMapping("/{id}/cancel")
    public Map<String, Object> cancel(
            @PathVariable Long id,
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            
            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            logger.info("Canceling order: {}, user: {}", id, userId);
            
            if (userId == null) {
                throw new RuntimeException("请先登录");
            }
            
            orderService.cancelOrder(id, userId);
            result.put("code", 200);
            result.put("message", "success");
        } catch (Exception e) {
            logger.error("Failed to cancel order: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @GetMapping("/{id}")
    public Map<String, Object> getOrderDetails(@PathVariable Long id,
                                                @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            
            // 从token中获取用户ID和角色
            Long userId = jwtUtil.getUserIdFromToken(token);
            Integer role = jwtUtil.getRoleFromToken(token);
            logger.info("Getting order details for order: {}, user: {}, role: {}", id, userId, role);
            
            if (userId == null) {
                throw new RuntimeException("请先登录");
            }
            
            Order order = orderService.getOrderDetails(id, userId, role); // 添加 role 参数
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", order);
        } catch (Exception e) {
            logger.error("Failed to get order details: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @GetMapping("/stats")
    public Map<String, Object> getOrderStats(
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            
            // 从token中获取用户ID和角色
            Long userId = jwtUtil.getUserIdFromToken(token);
            Integer role = jwtUtil.getRoleFromToken(token);
            logger.info("Getting order stats for user: {}, role: {}", userId, role);
            
            if (userId == null) {
                throw new RuntimeException("请先登录");
            }
            
            Map<String, Integer> stats = orderService.getOrderStats(userId, role);
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", stats);
        } catch (Exception e) {
            logger.error("Failed to get order stats: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @PostMapping("/{id}/restore")
    public Map<String, Object> restore(
            @PathVariable Long id,
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            
            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            logger.info("Restoring order: {}, user: {}", id, userId);
            
            if (userId == null) {
                throw new RuntimeException("请先登录");
            }
            
            orderService.restoreOrder(id, userId);
            result.put("code", 200);
            result.put("message", "success");
        } catch (Exception e) {
            logger.error("Failed to restore order: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @PostMapping("/{id}/confirm")
    public Map<String, Object> confirm(
            @PathVariable Long id,
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            logger.info("Extracted token: {}", token);
            
            // 从token中获取用户ID和角色
            Long userId = jwtUtil.getUserIdFromToken(token);
            Integer role = jwtUtil.getRoleFromToken(token); // 假设有方法获取角色
            logger.info("Confirming order: {}, user: {}, role: {}", id, userId, role);
            
            if (userId == null) {
                throw new RuntimeException("请先登录");
            }

            // 从数据库中查询用户姓名
            String customerName = userMapper.findNameById(userId); // 查询用户姓名

            // 从地址表中查询地址名称
            String addressName = addressMapper.findAddressNameByUserId(userId); // 查询地址名称

            // 假设送货确认人是当前用户
            String deliveryConfirmedBy = customerName; // 或者根据业务逻辑获取

            // 调用服务层确认订单
            orderService.confirmOrder(id, userId, customerName, addressName, deliveryConfirmedBy, role);
            result.put("code", 200);
            result.put("message", "success");
        } catch (Exception e) {
            logger.error("Failed to confirm order: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }
} 